// familyTreeUtil.js
// 终极横排分层版：每一层夫妻对/单身的所有子女同一排，不能递归拆散兄弟姐妹
export function buildCoupleTree(members) {
  if (!Array.isArray(members) || members.length === 0) return [];
  const memberMap = new Map();
  members.forEach(m => memberMap.set(m.id, { ...m }));

  // 找夫妻对
  const paired = new Set();
  const couples = [];
  members.forEach(m => {
    if (paired.has(m.id)) return;
    if (m.spouseId && memberMap.has(m.spouseId)) {
      const spouse = memberMap.get(m.spouseId);
      if (paired.has(m.spouseId)) return;
      if ((m.gender === '男' && spouse.gender === '女') || (m.gender === '女' && spouse.gender === '男')) {
        const husband = m.gender === '男' ? m : spouse;
        const wife = m.gender === '女' ? m : spouse;
        couples.push({ husband, wife });
        paired.add(m.id);
        paired.add(spouse.id);
      }
    }
  });
  const singles = members.filter(m => !paired.has(m.id));

  // 判断有无父母
  function hasParent(member) {
    return !!(member.fatherId || member.motherId || member.adoptedFatherId || member.adoptedMotherId);
  }
  let rootCouples = couples.filter(c => !hasParent(c.husband) && !hasParent(c.wife));
  let rootSingles = singles.filter(m => !hasParent(m));
  if (rootCouples.length === 0 && rootSingles.length === 0) {
    rootCouples = couples;
    rootSingles = singles;
  }

  // 获取某对父母的所有子女（同一排）
  function getChildrenRow(fatherId, motherId) {
    // 亲生+养子女 - 只要父或母有一个匹配即可
    const children = members.filter(child => {
      const matchFather = fatherId && (String(child.fatherId) === String(fatherId) || String(child.adoptedFatherId) === String(fatherId));
      const matchMother = motherId && (String(child.motherId) === String(motherId) || String(child.adoptedMotherId) === String(motherId));
      // 只要父母有一个匹配即可
      return matchFather || matchMother;
    }).map(child => ({
      ...child,
      adopted: !!(String(child.adoptedFatherId) == String(fatherId) && String(child.adoptedMotherId) == String(motherId))
    }));
    // 调试输出
    try {
      console.log('【getChildrenRow】查找父母', fatherId, motherId, '找到子女', children.map(c => c.name));
    } catch(e) {}

    // 夫妻对分组，配偶在全体成员中查找
    const paired = new Set();
    const couples = [];
    children.forEach(m => {
      if (paired.has(m.id)) return;
      if (m.spouseId && memberMap.has(m.spouseId)) {
        const spouse = memberMap.get(m.spouseId);
        if (paired.has(spouse.id)) return;
        if ((m.gender === '男' && spouse.gender === '女') || (m.gender === '女' && spouse.gender === '男')) {
          const husband = m.gender === '男' ? m : spouse;
          const wife = m.gender === '女' ? m : spouse;
          couples.push({ husband, wife });
          paired.add(m.id);
          paired.add(spouse.id);
        }
      }
    });
    const singles = children.filter(m => !paired.has(m.id));

    const row = [
      ...couples.map(c => ({
        type: 'couple',
        husband: c.husband,
        wife: c.wife,
        adopted: c.husband.adopted || c.wife.adopted,
        children: getChildrenRow(c.husband.id, c.wife.id)
      })),
      ...singles.map(s => ({
        type: 'single',
        person: s,
        adopted: s.adopted,
        children: getChildrenRow(s.id, null)
      }))
    ];
    return row;
  }

  // 只以"王老太爷+王老太太"为唯一根节点展开
  const rootHusband = members.find(m => m.name === '王老太爷');
  const rootWife = members.find(m => m.name === '王老太太');

  if (rootHusband && rootWife) {
    const result = [{
      type: 'couple',
      husband: rootHusband,
      wife: rootWife,
      children: getChildrenRow(rootHusband.id, rootWife.id)
    }];
    // 调试输出树结构
    try {
      console.log('【家谱树结构】', JSON.stringify(result, null, 2));
    } catch(e) {
      console.log('【家谱树结构】', result);
    }
    return result;
  }

  // 根节点递归
  const result = [
    ...rootCouples.map(c => ({
      type: 'couple',
      husband: c.husband,
      wife: c.wife,
      children: getChildrenRow(c.husband.id, c.wife.id)
    })),
    ...rootSingles.map(s => ({
      type: 'single',
      person: s,
      children: getChildrenRow(s.id, null)
    }))
  ];

  // 收集所有已挂载成员ID
  function collectIds(tree) {
    const ids = new Set();
    function traverse(node) {
      if (node.type === 'couple') {
        ids.add(node.husband.id);
        ids.add(node.wife.id);
        node.children.forEach(traverse);
      } else if (node.type === 'single') {
        ids.add(node.person.id);
        node.children.forEach(traverse);
      }
    }
    tree.forEach(traverse);
    return ids;
  }
  const usedIds = collectIds(result);

  // 把未挂载的成员补充为单节点
  const allIds = new Set(members.map(m => m.id));
  const unusedIds = [...allIds].filter(id => !usedIds.has(id));
  const unusedNodes = unusedIds.map(id => ({
    type: 'single',
    person: memberMap.get(id),
    children: []
  }));

  // 合并到最终结果
  const finalResult = [...result, ...unusedNodes];

  // 调试输出树结构
  try {
    console.log('【家谱树结构】', JSON.stringify(finalResult, null, 2));
  } catch(e) {
    console.log('【家谱树结构】', finalResult);
  }
  return finalResult;
} 